﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Security.Permissions;
using System.Security;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Windows.Forms;

namespace htmltortf
{
    class Criptografia
    {
        public bool EncryptConnStr()
        {
            
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ConfigurationSection section = config.ConnectionStrings;
        if (!section.SectionInformation.IsProtected)
        {
            if (!SIG.AppCode.UACSecurity.IsAdmin() )//&& SIG.AppCode.UACSecurity.IsVistaOrHigher())
            { SIG.AppCode.UACSecurity.RestartElevated(); }//Application.Exit(); }
            if (!SIG.AppCode.UACSecurity.IsAdmin() )//&& SIG.AppCode.UACSecurity.IsVistaOrHigher())
            { Application.Exit(); }
            
            config.ConnectionStrings.ConnectionStrings.Clear();
            ConnectionStringSettings css = new ConnectionStringSettings("htmltortf.Properties.Settings.igrejaConnectionString", "Data Source=|DataDirectory|\\igreja.sdf;password=@ilton11biblia", "Microsoft.SqlServerCe.Client.3.5");
            config.ConnectionStrings.ConnectionStrings.Add(css);

            //DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider protections possiveis
            section.SectionInformation.ProtectSection("dpapiProtectionConfigurationProvider");
            section.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);
            return true;
        }
        else { return false; }

            /*   '---indicate the section to protect
        Dim section As ConfigurationSection = _
           config.Sections("connectionStrings")
        '---specify the protection provider
        section.SectionInformation.ProtectSection(protectionProvider)
        '---Apple the protection and update
        config.Save()*/
        }
        public void DecryptConnStr()
        {
         Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ConfigurationSection section = config.ConnectionStrings;
        section.SectionInformation.UnprotectSection();
        config.Save();
        }
        public bool Permissao(string path)
        {
            try
            {
                ConfiguracaoTableAdapters.ConfiguracaoTableAdapter cta = new ConfiguracaoTableAdapters.ConfiguracaoTableAdapter();
                Configuracao.ConfiguracaoDataTable cdt = cta.GetDataById(1);
                //Configuracao.ConfiguracaoRow cr = (Configuracao.ConfiguracaoRow)cdt.Rows[0];
                cta.Update(cdt);
                //throw new Exception("fail");
                return false;
            }
            catch
            {
                if (!SIG.AppCode.UACSecurity.IsAdmin())//&& SIG.AppCode.UACSecurity.IsVistaOrHigher())
                { SIG.AppCode.UACSecurity.RestartElevated(); }//Application.Exit(); }
                if (!SIG.AppCode.UACSecurity.IsAdmin())//&& SIG.AppCode.UACSecurity.IsVistaOrHigher())
                { Application.Exit(); }
                try
                {
                    path = Directory.GetCurrentDirectory() + "\\" + path;
                    FileInfo fileInfo = new FileInfo(path);

                    FileSecurity fSecurity = File.GetAccessControl(path);
                    SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    //SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                    fSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify, AccessControlType.Allow));
                    //fSecurity.AddAccessRule(new FileSystemAccessRule(users, FileSystemRights.Modify, AccessControlType.Allow));
                    fileInfo.SetAccessControl(fSecurity);
                    //Environment.GetFolderPath(SpecialFolder.ApplicationData);
                }
                catch(Exception ex) {MessageBox.Show(ex.Message);}
                //return true;
                //foreach (FileSystemAccessRule rule in fSecurity.GetAccessRules(true, true, typeof(NTAccount)))
                //{
                  //  string s = "";
                //    StringBuilder bldr = new StringBuilder();
                //    if (rule.AccessControlType == AccessControlType.Deny)
                //        bldr.Append("[DENY] ");
                //    if (rule.IsInherited)
                //        bldr.Append("[INHERITED] ");
                //    bldr.AppendFormat("{0} ", rule.IdentityReference);
                //    bldr.Append(rule.FileSystemRights);
                //    Console.WriteLine(bldr.ToString());
                //}
                return true;
            }
            
            //File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.ReadOnly);
            //System.Security.AccessControl.FileSecurity fs = new System.Security.AccessControl.FileSecurity(path,AccessControlSections.All);

            // Add the FileSystemAccessRule to the security settings.
            //fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null).Value, FileSystemRights.FullControl, AccessControlType.Allow));

            // System.Security.AccessControl.DirectorySecurity sec =
            //System.IO.Directory.GetAccessControl(directory, AccessControlSections.All);
            //      FileSystemAccessRule accRule = new FileSystemAccessRule("Everyone",
            //                                           FileSystemRights.Modify,
            //                                         AccessControlType.Allow);
            //sec.AddAccessRule(accRule);    // setACL
            //sec.ResetAccessRule(accRule);

            //string str = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToUpper();
            //foreach (System.Security.AccessControl.FileSystemAccessRule rule in fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            //{
            //if (str == rule.IdentityReference.Value.ToUpper())
            //      rule.AccessControlType = System.Security.AccessControl.AccessControlType.Allow;
            //&& (fileSystemRights == (rule.FileSystemRights & fileSystemRights)));
            //} 
            //'---open the web.config file
            //FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, Directory.GetCurrentDirectory()+"\\igreja.sdf");
            //f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
            //try
            //{
            //    f2.Demand();
            //}
            //catch (SecurityException s)
            //{
            //    Console.WriteLine(s.Message);
            //}   
        
        }
    }
}
